package com.groupbuying.payproducer.aliPay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeCreateRequest;
import com.alipay.api.response.AlipayTradeCreateResponse;
import com.groupbuying.payproducer.utils.JSONUtils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 阿里云支付基础类
 *
 * @Author Vincentxin
 * @Date 2019-07-10
 */
public class AliPay {
    /**
     * 创建统一支付单
     *
     * @param bizContent 支付参数
     * @param initParam  初始化SDK的支付基础参数
     * @return
     */
    public static String aliPayCreate(Map<String, String> bizContent, Map<String, String> initParam) {
        //初始化SDK的支付基础参数
        AlipayClient alipayClient = new DefaultAlipayClient(
                initParam.get(AliPayNativeConstants.URL),
                initParam.get(AliPayNativeConstants.APP_ID),
                initParam.get(AliPayNativeConstants.APP_PRIVATE_KEY),
                initParam.get(AliPayNativeConstants.FORMAT),
                initParam.get(AliPayNativeConstants.CHARSET),
                initParam.get(AliPayNativeConstants.ALIPAY_PUBLIC_KEY),
                initParam.get(AliPayNativeConstants.SIGN_TYPE)
        );
        AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
        //TODO 设置异步回执地址
        request.setNotifyUrl(initParam.get(AliPayNativeConstants.NOTIFY_URL));
        request.setBizContent(JSONUtils.beanToJson(bizContent));
        String trade_no = "";
        try {
            //使用的是execute
            AlipayTradeCreateResponse response = alipayClient.execute(request);
            trade_no = response.getTradeNo();//获取返回的tradeNO。
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return trade_no;
    }

    /**
     * 原生支付宝异步回执签名验证
     *
     * @param param     回执参数
     * @param initParam 请求出实话参数
     * @return
     */
    public static Map<String, String> aliPayCallBackVerify(Map<String,String> param, Map<String, String> initParam) {
        Map<String, String> params = new HashMap<>();
        try {
            boolean flag = AlipaySignature.rsaCheckV1(param, initParam.get(AliPayNativeConstants.ALIPAY_PUBLIC_KEY), initParam.get(AliPayNativeConstants.CHARSET), "RSA2");
            params.putAll(param);
            params.put("flag", flag == true ? "true" : "false");
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return params;
    }


}
